package com.study.chapter06;

import com.study.entity.Event;
import com.study.chapter05.source.ClickSource;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.time.Duration;

/**
 * @Description:
 * @Author: LiuQun
 * @Date: 2022/8/1 22:41
 */
public class WatermarkTest {

    public static void main(String[] args) throws Exception {
        //环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        DataStreamSource<Event> stream = env.fromElements(
                new Event("Bob", "./home", 1000L),
                new Event("Livy", "./home", 2000L),
                new Event("Alice", "./cart", 3000L),
                new Event("Bob", "./cart", 2000L),
                new Event("Livy", "./prod?id=20", 4000L),
                new Event("Bob", "./prod?id=30", 5000L),
                new Event("Bob", "./home", 6000L),
                new Event("Alice", "./home/car", 7000L)
        );
        DataStreamSource<Event> stream2 = env.addSource(new ClickSource()).setParallelism(1);

        //1.有序流的watermark生成
        WatermarkStrategy<Event> watermarkStrategy = WatermarkStrategy.<Event>forMonotonousTimestamps()
                .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                    @Override
                    public long extractTimestamp(Event element, long recordTimestamp) {
                        //抽取时间戳的逻辑
                        return element.timestamp;
                    }
                });
        SingleOutputStreamOperator<Event> operator = stream.assignTimestampsAndWatermarks(watermarkStrategy);

        //无序流的watermark生成
        WatermarkStrategy<Event> watermarkStrategy2 = WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ofSeconds(5)) //延时设置为5s
                .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                    @Override
                    public long extractTimestamp(Event element, long recordTimestamp) {
                        //抽取时间戳的逻辑
                        return element.timestamp;
                    }
                });
        SingleOutputStreamOperator<Event> operator2 = stream2.assignTimestampsAndWatermarks(watermarkStrategy2);

        stream.print();
        stream2.print();

        env.execute();
    }

}
